package com.chenwy.example.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import java.io.IOException;
import java.util.concurrent.Callable;
@RestController
@RequestMapping(value = "test")
//@Slf4j
public class TestController{

    private SseEmitter sseEmitter = new SseEmitter();

    @RequestMapping(value = "testSseEmitter",method = RequestMethod.GET)
    public SseEmitter testSseEmitter(){
        return sseEmitter;
    }

    @RequestMapping(value="setSseEmitter",method = RequestMethod.GET)
    public String setSseEmitter(){
        try {
            sseEmitter.send(System.currentTimeMillis());
        } catch (IOException e) {
            e.printStackTrace();
            return "Error";
        }
        return "Succeed!";
    }

    @RequestMapping(value="completeSseEmitter",method = RequestMethod.GET)
    public String completeSseEmitter(){
        sseEmitter.complete();
        return "Succeed!";
    }

    @GetMapping(value="download")
    public StreamingResponseBody handle(){
        return (outputStream)->{

        };
    }


    private DeferredResult<String> deferredResult = new DeferredResult<>();

    @RequestMapping(value="testDeferredResult",method = RequestMethod.GET)
    public DeferredResult<String> testDeferredResult(){
        return deferredResult;
    }

    @RequestMapping(value="setDeferredResult",method = RequestMethod.GET)
    public String setDeferredResult(){
        deferredResult.setResult("Test Result!");
        return "succeed";
    }

    @RequestMapping(value="testCallable",method = RequestMethod.GET)
    public Callable<String> testCallable(){
//        log.info("================testCallable");
        Callable<String> callable = () ->{
            Thread.sleep(5000);
            return "succeed";
        };
        return callable;
    }
}
